import {DeepChat} from 'deep-chat-react';
import './style.css';
import {sendChatRequest} from "../../apis/mindchat.js";
import {useState} from "react";
import {baseURL} from "../../utils/request.js";


const MindChat = () => {

    const [allMessages, setAllMessages] = useState([
        {role: 'user', text: 'Hey, how are you today?'},
        {role: 'ai', text: 'I am doing very well!'},
    ])


    let [tempMessage, setTempMessage] = useState([
        {role: 'system', content: 'I am doing very well!'},
        {role: 'user', content: 'Hey, how are you today?'},
    ])


    const sendMessage = async (signal) => {


        const resp = await fetch(baseURL + '/api/v1/chat/completions', {
            method: 'post',
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
                Authorization: window.localStorage.getItem('token'),
            },
            body: JSON.stringify(
                {
                    model: window.localStorage.getItem('gpt'),
                    messages: tempMessage,
                }
            )
        })

        const reader = resp.body.getReader()


        let tempDrewContentData = ''
        const textDecoder = new TextDecoder()
        while (1) {
            const {done, value} = await reader.read()
            if (done) {
                break
            }
            const str = textDecoder.decode(value)
            console.log('对话', str)

            tempDrewContentData += str
        }

        let  data = {
            role:'system',
            content:tempDrewContentData
        }

        tempMessage.push(data)

        signal.onResponse({text: tempDrewContentData})

    }
    return (
        <>
            <div className='chatBox'>
                <DeepChat
                    demo={true}
                    style={{
                        borderRadius: '10px',
                        width: '80vw',
                        height: '90%',
                        transform: 'translateX(-100px)'
                    }}
                    request={{
                        handler: (body, signal) => {
                            sendMessage(signal)
                        }
                    }}
                   requestInterceptor={(body) => {
                       console.log('body',body.body.messages[0])
                       let data = body.body.messages[0]
                       data.content = data.text
                        delete  data.text
                       tempMessage.push(data)
                   }}

                    textInput={{placeholder: {text: '开始聊天吧!'}}}
                    initialMessages={allMessages}
                />
            </div>

        </>
    )
}

export default MindChat